#coding:utf8
from __future__ import print_function, division, absolute_import
import numpy as np
import tensorflow as tf
import tflearn
from tflearn.data_utils import shuffle, to_categorical
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.estimator import regression
from common.load import *
from common.data_generator import *

# dB = 25
# smoothingLen = 127
# X, Y, x, y = generateData(30000, 20000, dB, smoothingLen, 5, 'cnn') # X (19990,2); Y (19990, 4)
# print(type(X))
# print(X[0][0].shape)
test = np.loadtxt('../test.txt')     #32768 接收端
send = np.loadtxt('../send.txt')     # 2 * 4096

def yinshe(p):
	tmp = [0 for i in range(9)]
	x,y = [1 if (a < 0.5 and a > -0.5) else 2 if a>0 else 0 for a in p]
	tmp[3*x+y] = 1
	return tmp

send = np.array(send).T
send = np.vstack((send,send,send,send))


Y = np.array(map(yinshe, send))  #label


X = np.vstack((test[1::2], test[::2])).T   # 接收端收到的数据 16384 * 2
tmp = []
for i in range(4096*4-127):
	tmp.append(np.array(X[i:i+128]).T)
X = np.array(tmp)

print(X.shape,Y.shape)  #(16384, 2) (16384, 9)
X,Y = X.tolist()[:16000],Y.tolist()[:16000]
for i in range(len(X)):
	for j in range(len(X[0])):
		X[i][j] = np.array(X[i][j]).reshape(128,1)
print(X[0][1].shape)


labels = [str(i) for i in range(1,10)]

def shuffle_in_unison_inplace(a, b):
	assert len(a) == len(b)
	p = np.random.permutation(len(a))
	return a[p], b[p]

# X, Y = shuffle_in_unison_inplace(np.array(X), np.array(Y))

config = tf.ConfigProto(allow_soft_placement=True)

CNN1 = True

with tf.Session(config=config) as sess:

	network = input_data(shape=[2,128,1], name="inp")

	if CNN1:
		network = conv_2d(network, 64, [1,3], activation="relu", name="conv1")
		network = conv_2d(network, 16, [2,3], activation="relu", name="conv2")
		network = fully_connected(network, 128, activation='relu', name="fully")
		network = dropout(network, 0.5, name="drop1")

	network = fully_connected(network, 9, activation='softmax', name="out")
	outputs = tf.constant(labels, name="outputs1")
	strout = tf.gather(outputs, tf.argmax(network, 0), name="outputs2")

	network = regression(network, optimizer='adam',
						loss='categorical_crossentropy',
						learning_rate=0.001)

	model = tflearn.DNN(network, session=sess, tensorboard_verbose=0)

	ops = tf.initialize_all_variables()
	sess.run([ops, outputs])

	model.fit(X, Y, n_epoch=10, validation_set=0.0, shuffle=True, show_metric=True, batch_size=1024, run_id='equalizer_cnn')

	sess.run(outputs)

	gd = 0
	for v, w in zip(X, Y):
		if np.argmax(model.predict([v])[0]) == np.argmax(w):
			gd += 1
<<<<<<< HEAD:src/main3_cnn.py
	print("Accuracy:", gd/len(Y))
=======
	print("Accuracy:", gd/len(y))
>>>>>>> d0274871dc5db9d9864240ff5fbea611b1e64a05:src/main3_cnn.py
